package com.basin.common.oss.component;

import com.basin.common.oss.property.QiNiuConfigProps;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @author: Sam ZHONG | sammy1997@aliyun.com
 */
@Component
@EnableConfigurationProperties(QiNiuConfigProps.class)
@Slf4j
public class BasinUploadManager {

    @Resource
    private QiNiuConfigProps qiNiuConfigProps;

    /**
     * 返回访问连接
     *
     * @param fileName fileName
     * @param data     data
     * @return url
     */
    public String upload(String fileName, byte[] data) {
        UploadManager uploadManager = new UploadManager(new Configuration());
        Auth auth = Auth.create(this.qiNiuConfigProps.getAccessKey(),
                this.qiNiuConfigProps.getSecretKey());
        String token = auth.uploadToken(this.qiNiuConfigProps.getBucket());

        try {
            Response response = uploadManager.put(data, fileName, token);

            DefaultPutRet pet = response.jsonToObject(DefaultPutRet.class);

            String key = pet.key;
            String encodedFileName = URLEncoder.encode(key, StandardCharsets.UTF_8)
                    .replace("+", "%20");

            return String.format("%s/%s", this.qiNiuConfigProps.getDomain(), encodedFileName);
        } catch (QiniuException e) {
            log.error("上传到七牛云存储失败 {}", e.response.toString());
            throw new RuntimeException(e);
        }
    }
}
